//
//  SetGuestDateTimeViewController.m
//  QRMaster
//
//  Created by myApple on 15/7/22.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "SetGuestDateTimeViewController.h"

#import "PromptInfoView.h"
#import "DateSelectViewController.h"
#import "guestTimeModel.h"
#import "guestTimeCell.h"
#import "RequestNetWork.h"
#import "Reachability.h"
#import "MJExtension.h"
#import "IQKeyboardManager.h"

@interface SetGuestDateTimeViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView * guestRoomTableView;
    NSMutableArray * guestRoomArray;
    NSMutableArray * selectToSetTimeArray;//将要设置时间的房间，设置完后置空
    BOOL allSelectFlag;//全选的标识
    
    UIActivityIndicatorView * _activityIndicator;
    
    UIView * promtView;
    
    //多语言
    UILabel * titleLabel;
    UIButton * selectAllBtn;
    UIButton * setDateTimeBtn;
    UILabel * promtTextLabel;
}

@end

@implementation SetGuestDateTimeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        guestRoomArray = [[NSMutableArray alloc]init];
        selectToSetTimeArray = [[NSMutableArray alloc]init];
        allSelectFlag  = false;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = NSLocalizedString(@"setTime", nil);
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    // Do any additional setup after loading the view.
//    [self prepareTitleView];
    [self prepareTableView];
    [self prepareActivityIndicator];
    [self prepareViewWithNoRoom];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    titleLabel.text = NSLocalizedString(@"setTime", nil);
    [selectAllBtn setTitle:NSLocalizedString(@"selectAll", nil) forState:0];
    [setDateTimeBtn setTitle:NSLocalizedString(@"setTime", nil) forState:0];
    promtTextLabel.text = NSLocalizedString(@"allocateRoom", nil);
    [selectToSetTimeArray removeAllObjects];
    selectAllBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    selectAllBtn.hidden = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

-(void)setCommunity:(NSString *)community
{
    _community = community;
    if ([self IsHaveNetwork]) {
        return;
    }
    [_activityIndicator startAnimating];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_community forKey:@"communityId"];
    [postDict setValue:_guestId forKey:@"userId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(GETCLIENTROOMS) params:postDict block:^(id downLoadData, id error)
    {
        [_activityIndicator stopAnimating];
        if ([downLoadData objectForKey:@"data"]) {
            for (NSDictionary * dict in [downLoadData objectForKey:@"data"]) {
                guestTimeModel * model = [[guestTimeModel alloc]init];
//                model = [guestTimeModel mj_objectWithKeyValues:dict];
                
                model.buildId = [dict objectForKey:@"buildId"];
                model.buildName = [dict objectForKey:@"buildName"];
                model.floorId = [dict objectForKey:@"floorId"];
                model.floorName = [dict objectForKey:@"floorName"];
                model.roomId = [dict objectForKey:@"roomId"];
                model.roomName = [dict objectForKey:@"roomName"];
                model.beginTime = [dict objectForKey:@"startTime"];
                model.endTime = [dict objectForKey:@"endTime"];
                [guestRoomArray addObject:model];
                [guestRoomTableView reloadData];
            }
        }
        else
        {
            if ([[error objectForKey:@"status"]intValue]==301) {
                promtView.hidden = NO;
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
        }
    }];


}

-(void)prepareTitleView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = 20;

    selectAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectAllBtn.frame = CGRectMake(UI_SCREEN_WIDTH-100, 0, 100, 40);
    [selectAllBtn setTitle:NSLocalizedString(@"selectAll", nil) forState:0];
    selectAllBtn.selected = NO;
    selectAllBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [selectAllBtn addTarget:self action:@selector(selectAllCell:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:selectAllBtn];
    
    
    x = 0;
    y = ScreenHeight - 50-64;
    width = ScreenWidth;
    height = 50;
    UIView * setDateTimeView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    setDateTimeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:setDateTimeView];
    
    x = 20;
    y = 5;
    width = ScreenWidth - 2 * x;
    height = 40;
    setDateTimeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    setDateTimeBtn.frame = CGRectMake(x, y, width, height);
    [setDateTimeBtn setTitle:NSLocalizedString(@"setTime", nil) forState:0];
    setDateTimeBtn.layer.cornerRadius = 5;
    setDateTimeBtn.layer.masksToBounds = YES;
    [setDateTimeBtn setBackgroundColor:[UIColor clearColor]];
    [setDateTimeBtn setTitleColor:RGBA(125, 194, 52, 1) forState:0];
    setDateTimeBtn.layer.borderColor = RGBA(125, 194, 52, 1).CGColor;
    setDateTimeBtn.layer.borderWidth = 1.0;
    [setDateTimeBtn addTarget:self action:@selector(setDateTime) forControlEvents:UIControlEventTouchUpInside];
    [setDateTimeView addSubview:setDateTimeBtn];
}

//全选
-(void)selectAllCell:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        allSelectFlag = true;
        [guestRoomTableView reloadData];
        [selectToSetTimeArray removeAllObjects];
        [btn setTitle:NSLocalizedString(@"selectNone", nil)forState:0];
        for (int i = 0 ; i < guestRoomArray.count; i ++) {
            [selectToSetTimeArray addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    else
    {
         [btn setTitle:NSLocalizedString(@"selectAll", nil) forState:0];
        [selectToSetTimeArray removeAllObjects];
        allSelectFlag = false;
        [guestRoomTableView reloadData];
        
    }
    
    
}

//设置时间
-(void)setDateTime
{
    if (selectToSetTimeArray.count < 1) {
        [PromptInfoView showMessage:NSLocalizedString(@"chooseRoom", nil) superView:self.view];
        return;
    }
    DateSelectViewController * dpvc = [[DateSelectViewController alloc]init];
    dpvc.communityId = _community;
    dpvc.guestId = _guestId;
    dpvc.roomInfo = guestRoomArray;
    dpvc.selectRoom = selectToSetTimeArray;
    dpvc.getTime = ^(NSString * begtime,NSString * endtime)
    {
        for (int i = 0 ; i < selectToSetTimeArray.count; i ++) {
            NSInteger index = [selectToSetTimeArray[i]integerValue];
            guestTimeModel * model = guestRoomArray[index];
            model.beginTime = begtime;
            model.endTime = endtime;
            [guestRoomArray replaceObjectAtIndex:index withObject:model];
        }
        [selectToSetTimeArray removeAllObjects];
        [guestRoomTableView reloadData];
    };
    [self.navigationController pushViewController:dpvc animated:YES];
   
}

-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - 64;
    
    guestRoomTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    guestRoomTableView.dataSource = self;
    guestRoomTableView.delegate = self;
    guestRoomTableView.tableFooterView = [[UIView alloc]init];
    guestRoomTableView.bounces = NO;
    [self.view addSubview:guestRoomTableView];
    
    y = 0;
    height = 16;
    UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    headView.backgroundColor = self.view.backgroundColor;
    guestRoomTableView.tableHeaderView = headView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return guestRoomArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    guestTimeCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[guestTimeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (guestRoomArray.count > indexPath.row) {
        guestTimeModel * model = guestRoomArray[indexPath.row];
        cell.buildName = model.buildName;
        cell.buildId = model.buildId;
        cell.floorName = model.floorName;
        cell.floorId = model.floorId;
        cell.roomName = model.roomName;
        cell.roomId = model.roomId;
        cell.beginTime = model.beginTime;
        cell.endTime = model.endTime;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
//    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
//        cell.accessoryType = UITableViewCellAccessoryNone;
//        [selectToSetTimeArray removeObject:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
//    }
//    else
//    {
//        cell.accessoryType = UITableViewCellAccessoryCheckmark;
//        [selectToSetTimeArray addObject:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
//    }
     [selectToSetTimeArray addObject:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
    [self setDateTime];
}


-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(self.view.frame.size.width / 2.0 -15, self.view.frame.size.height / 2.0 - 15, 30, 30);
    _activityIndicator.hidden = NO;
    [self.view addSubview:_activityIndicator];
}

-(void)prepareViewWithNoRoom
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float width;
    float height;
    
    promtView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    promtView.backgroundColor = RGBA(237, 238, 241, 1);
    promtView.hidden = YES;
    [self.view addSubview:promtView];
    
    NSString * imgPath = [[NSBundle mainBundle]pathForResource:@"没有设置默认房卡" ofType:@"png"];
    UIImage * promImg = [UIImage imageWithContentsOfFile:imgPath];
    height= promImg.size.height * ScreenWidth / 3.0 /promImg.size.width;
    width = ScreenWidth / 3.0;
    UIImageView * promImgView = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - width)/ 2.0, (self.view.frame.size.height - height)/ 2.0 - 64, width, height)];
    promImgView.image = promImg;
    [promtView addSubview:promImgView];
    
    
    promtTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, promImgView.frame.size.height /2.0+promImgView.frame.origin.y + 74, ScreenWidth - 100, 60)];
    promtTextLabel.text = NSLocalizedString(@"allocateRoom", nil);
    promtTextLabel.textColor = RGBA(211, 211, 211, 1);
    promtTextLabel.textAlignment = NSTextAlignmentCenter;
    promtTextLabel.numberOfLines = 0;
    promtTextLabel.font = [UIFont systemFontOfSize:16.0];
    [promtView addSubview:promtTextLabel];

}

//判断是否有网络
-(BOOL)IsHaveNetwork
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if([reach currentReachabilityStatus] == NotReachable) {
        [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        return YES;
    }
    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
